#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright: (c)  : @Time 2025/3/29 08  @Author  : hjl
# @Site    : 
# @File    : log.py
# @Project: alibaba_spider
# @Software: PyCharm
# @Desc    :
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# !/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os
import shutil
import vault as c

if not os.path.isdir(c.log_path):
    os.makedirs(c.log_path)
log_file = c.BASE_DIR + os.path.join(c.log_path, c.log_name)


class DIYLog(object):
    """
    自定义日志
    """

    def __init__(self, message=None, logfile=log_file, logfmt=None):
        """
        :param message:
        :param logfile:
        :param logfmt:
        """
        self.logfmt = "%(asctime)s %(levelname)s %(name)s %(message)s" if logfmt is None else logfmt
        self.logfile = logfile
        if os.path.isdir(self.logfile):
            shutil.rmtree(self.logfile)
        if not os.path.isfile(self.logfile):
            with open(self.logfile, "w") as f:
                f.write("")
        self.message = message
        self.logger = logging.getLogger("diylog")
        self.logger.setLevel(c.log_level)
        # 添加控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.DEBUG)
        console_handler.setFormatter(logging.Formatter(self.logfmt))
        self.logger.addHandler(console_handler)

    def debug(self, message=None):
        fd = logging.FileHandler(self.logfile)
        fd.setLevel(logging.DEBUG)
        fd.setFormatter(logging.Formatter(self.logfmt))
        self.logger.addHandler(fd)
        self.logger.debug(message)
        self.logger.removeHandler(fd)

    def info(self, message=None):
        fd = logging.FileHandler(self.logfile)
        fd.setLevel(logging.INFO)
        fd.setFormatter(logging.Formatter(self.logfmt))
        self.logger.addHandler(fd)
        self.logger.info(message)
        self.logger.removeHandler(fd)

    def warning(self, message=None):
        fd = logging.FileHandler(self.logfile)
        fd.setLevel(logging.WARNING)
        fd.setFormatter(logging.Formatter(self.logfmt))
        self.logger.addHandler(fd)
        self.logger.warning(message)
        self.logger.removeHandler(fd)

    def error(self, message=None):
        fd = logging.FileHandler(self.logfile)
        fd.setLevel(logging.ERROR)
        fd.setFormatter(logging.Formatter(self.logfmt))
        self.logger.addHandler(fd)
        self.logger.error(message)
        self.logger.removeHandler(fd)


# if __name__ == '__main__':
#     diylog = DIYLog()
#     diylog.debug("hello debug")
#     diylog.info("hello world")
